package com.taomu.app.zongchouhuli.http.api;

import android.util.Log;
import android.widget.Toast;

import com.alibaba.fastjson.JSONException;
import com.taomu.app.zongchouhuli.framework.BaseView;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import io.reactivex.Observer;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

public abstract class HttpObserver<T> implements Observer<T> {

    private boolean showLoading;

    private CompositeDisposable compositeDisposable;

    private BaseView baseView;

    public HttpObserver(BaseView baseView, CompositeDisposable compositeDisposable, boolean showLoading){
        this.compositeDisposable = compositeDisposable;
        this.showLoading = showLoading;
        this.baseView = baseView;
    }

    @Override
    public void onSubscribe(Disposable d) {
        compositeDisposable.add(d);
        showLoading();
    }


    @Override
    public void onError(Throwable e) {
        //todo:处理错误信息
        dimissLoading();
        if (e instanceof SocketTimeoutException) {
            showToast("网络中断，请检查您的网络状态");
        } else if (e instanceof ConnectException) {
            showToast("网络中断，请检查您的网络状态");
        } else if(e instanceof JSONException){
            showToast("数据解析失败");
        } else if("411".equals(e.getMessage())){
            showTokenDialog();
        } else{
            showToast(e.getMessage());
        }

    }

    @Override
    public void onComplete() {
        dimissLoading();
    }

    private void showLoading(){
        if(baseView != null){
            baseView.showLoadingDialog();
        }
    }

    private void dimissLoading(){
        if(baseView != null){
            baseView.dismissLoadingDialog();
        }
    }

    private void showToast(String msg){
        if(baseView != null){
            Log.d("dwqdwqdqdwqd","msg:"+msg);
            baseView.showToast(msg);
        }
    }

    private void showTokenDialog(){
        if(baseView != null){
           baseView.showToken();
        }
    }
}
